/**
 * 
 */
package com.runningfox.logic;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import android.content.Context;
import android.util.Log;

import com.runningfox.humor.Action;
import com.runningfox.humor.ProcessCallback;
import com.runningfox.model.Joke;
import com.runningfox.model.ResultSet;
import com.runningfox.model.Setting;

/**
 * @author lhy
 * 
 */
public class Logic {
	public static Context c;
	public static final int timeout = 10000;
	// public static final String urlServer = "http://192.168.133.80:8000/";
	// public static final String SERVER = "http://192.168.1.102:8000/";
	// 192.168.0.161
	// public static final String SERVER = "http://192.168.0.161:8000/";
	// public static final String urlServer = "http://10.0.2.2:8000/"; //for
	// emulator localhost
	public static final String SERVER = "http://lhy.kync.com/";
	public static final String SERVER1 = "http://joke.haiyanglu.com/";
	public static final String GET = "GET";
	public static final String SYNC = "humor/sync/";
	public static final String HOME = "humor/home/";
	public static final String REFRESHHOME = "humor/refreshhome/";
	public static final String MORE = "humor/more/";
	public static final String MOREBYID = "humor/morebyid/";
	public static final String LIKE = "humor/like/";
	public static final String HATE = "humor/hate/";
	public static final String OLD = "old/";
	public static final String STAR = "humor/star/";
	public static final String UNSTAR = "humor/unstar/";
	public static final String VIEW = "humor/view/";
	public static final String VIEWCOMMENT = "humor/viewcomment/";
	public static final String COMMENT = "humor/postcomment/";
	public static final String CHANGEUSERNAME = "humor/changeusername/";

	public static void loadComments(Joke node, String page,
			ProcessCallback callback) {
		if (page == null) {
			page = "0";
		}
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(VIEWCOMMENT)
				+ page, callback);
		if (is != null) {
			ResultSet res;
			res = Parser.parse(is, callback);
			res.action = Action.LOADCOMMENT;
			callback.onSucess(res);
		} else {
			ResultSet res = new ResultSet();
			res.action = Action.HOME;
			callback.onFailed(res);
		}

	}

	public static String genURL(String url) {
		return SERVER + url + Setting.userid + '/';
	}

	public static void saveFavourite(Joke node) {
		DataBase db = new DataBase(c);
		db.saveFavouriteJoke(node);
	}

	public static void getFavouriteJoke(ProcessCallback callback) {
		DataBase db = new DataBase(c);
		ArrayList<Joke> list = db.getFavouriteJokes();
		ResultSet res = new ResultSet();
		res.jokeList = list;
		callback.onSucess(res);
	}

	/**
	 * 读取未读笑话
	 * 
	 * @param callback
	 */
	public static void getUnreadJoke(ProcessCallback callback) {
		DataBase db = new DataBase(c);
		ArrayList<Joke> list = db.getUnreadJokes();
		ResultSet res = new ResultSet();
		res.jokeList = list;
		callback.onSucess(res);
	}

	/**
	 * 读取已读笑话
	 * 
	 * @param callback
	 */
	public static void getReadJoke(ProcessCallback callback) {
		DataBase db = new DataBase(c);
		ArrayList<Joke> list = db.getReadJokes();
		ResultSet res = new ResultSet();
		res.jokeList = list;
		callback.onSucess(res);
	}

	/**
	 * 将笑话内容保存到文件缓存
	 * 
	 * @param node
	 */
	public static void saveJokeDetail(Joke node) {
		DataBase db = new DataBase(c);
		db.updateOrInsertJokeNode(node);
		Cache c = Cache.getInstance();
		c.putString(String.valueOf(node.id), node.html);
	}

	/**
	 * 保存更新笑话
	 * 
	 * @param node
	 */
	public static void saveJoke(Joke node) {
		DataBase db = new DataBase(c);
		db.updateOrInsertJokeNode(node);
	}

	/**
	 * 从缓存文件里面读取笑话
	 * 
	 * @param node
	 *            笑话节点，里面包含笑话的id来确定缓存文件名字
	 * @return 返回笑话html字符内容
	 */
	public static String getJokeNodeCacheHTML(Joke node) {
		/*
		 * DataBase db = new DataBase(c); return
		 * db.getJokeHTML(String.valueOf(node.id));
		 */
		Cache c = Cache.getInstance();
		return c.getString(String.valueOf(node.id));
	}

	public static void updateAllJokes(ArrayList<Joke> list) {
		Log.v("debug", "updateAllJokes");
		if (list == null || list.size() <= 0) {
			return;
		}
		DataBase db = new DataBase(c);
		db.updateAllJokes(list);
	}

	public static ArrayList<Joke> loadJokeListFromCache() {
		DataBase db = new DataBase(c);
		return db.getAllJokes();
	}

	
	public static void reFreshHomePage(ProcessCallback callback) {
		InputStream is = StreamToolBox
				.loadStreamFromURL(genURL(REFRESHHOME), callback);
		if (is != null) {
			ResultSet res;
			res = Parser.parse(is, callback);
			if(res!=null){
				res.action = Action.HOME;
				callback.onSucess(res);
			}
		} else {
			ResultSet res = new ResultSet();
			res.action = Action.HOME;
			callback.onFailed(res);
		}
	}
	public static void requestHomePage(ProcessCallback callback) {
		InputStream is = StreamToolBox
				.loadStreamFromURL(genURL(HOME), callback);
		if (is != null) {
			ResultSet res;
			res = Parser.parse(is, callback);
			if(res!=null){
				res.action = Action.HOME;
				callback.onSucess(res);
			}
		} else {
			ResultSet res = new ResultSet();
			res.action = Action.HOME;
			callback.onFailed(res);
		}
	}

	/**
	 * 通过页码方式读取更更多笑话
	 * 
	 * @param callback
	 * @param page
	 */
	public static void requestJokesByPage(ProcessCallback callback, String page) {
		if (page == null) {
			callback.onFailed(null);
			return;
		}
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(MORE) + page,
				callback);
		if (is != null) {
			ResultSet res = Parser.parse(is, callback);
			if (res != null) {
				res.action = Action.MORENET;
				callback.onSucess(res);
			}
		} else {
			ResultSet res = new ResultSet();
			res.action = Action.HOME;
			callback.onFailed(res);
		}
	}

	/**
	 * 通过hid方式读取更多笑话
	 * 
	 * @param callback
	 * @param hid
	 */
	public static void requestMoreJokesById(ProcessCallback callback, String hid) {
		if (hid == null) {
			callback.onFailed(null);
			return;
		}
		InputStream is = StreamToolBox.loadStreamFromURL(
				genURL(MOREBYID) + hid, callback);
		if (is != null) {
			ResultSet res = Parser.parse(is, callback);
			if (res != null) {
				res.action = Action.MORENET;
				callback.onSucess(res);
			}
		} else {
			ResultSet res = new ResultSet();
			res.action = Action.HOME;
			callback.onFailed(res);
		}
	}

	/**
	 * 通过hid方式读取更多笑话
	 * 
	 * @param callback
	 * @param hid
	 */

	public static boolean requestMoreJokesFromDataBase(String hid,
			ProcessCallback callback) {
		DataBase db = new DataBase(c);
		ArrayList<Joke> list = db.getMoreJokeNodes(hid);
		ResultSet res = new ResultSet();
		res.jokeList = list;
		if (list != null && list.size() > 0) {
			callback.onSucess(res);
			return true;
		} else {
			return false;
		}
	}

	public static void synchronJokes(ProcessCallback callback) {
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(SYNC)
				+ Setting.contentVersion, callback);
		if (is != null) {
			ResultSet res;
			res = Parser.parse(is, callback);
			res.action = Action.HOME;
			DataBase db = new DataBase(c);
			db.saveAll(res.jokeList);
			callback.onSucess(res);
		} else {
			ResultSet res = new ResultSet();
			res.action = Action.HOME;
			callback.onFailed(res);
		}

		genTestData();
	}

	static void genTestData() {
		ArrayList<Joke> list = new ArrayList<Joke>();
		for (int i = 0; i < 10; i++) {
			Joke n = new Joke();
			n.datetime = new Date();
			n.body = "body" + n.datetime;
			n.id = (int) (n.datetime.getTime());
			n.read = 0;
			n.star = 0;
			n.tag = "tag" + n.datetime;
			n.title = "title" + n.datetime;
			n.url = "url" + n.datetime;
			n.user = "urser" + n.datetime;
			list.add(n);
		}
		DataBase db = new DataBase(c);
		db.saveAll(list);

	}

	public static void requestLike(ProcessCallback callback, int id) {
		ResultSet res = new ResultSet();
		res.action = Action.LIKE;
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(LIKE) + id,
				callback);
		if(is!=null){
			res = Parser.parse(is, callback);
			ArrayList<Joke> jokelist = res.jokeList;
			if (jokelist != null && jokelist.size() > 0) {
				callback.onSucess(res);
			} else {
				callback.onFailed(res);
			}
		}
	}

	public static void requestDisLike(ProcessCallback callback, int id) {
		ResultSet res = new ResultSet();
		res.action = Action.LIKE;
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(HATE) + id,
				callback);
		try {
			res.dislike = StreamToolBox.loadStringFromStream(is);
			callback.onSucess(res);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			callback.onFailed(res);
		}
	}

	public static void reqeustDetail(ProcessCallback callback, Joke node) {
		String url = null;
		if (node.url.startsWith("http")) {
			url = node.url;
		} else {
			url = genURL(VIEW) + node.url;
		}
		InputStream is = StreamToolBox.loadStreamFromURL(url, callback);
		try {
			if (is != null) {
				String html = StreamToolBox.extractGZipStreamToString(is);
				ResultSet res = new ResultSet();
				res.action = Action.DETAIL;
				if (html != null) {
					res.html = html;
					callback.onSucess(res);
				} else {
					callback.onFailed(res);
				}
			} else {
				callback.onHttp404();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void reqeustOld(ProcessCallback callback, int id) {
		ResultSet res = new ResultSet();
		res.action = Action.DETAIL;
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(OLD) + id,
				callback);
		try {
			res.html = StreamToolBox.loadStringFromStream(is);
			callback.onSucess(res);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			callback.onFailed(res);
		}
	}

	/**
	 * 删除收藏的笑话
	 * 
	 * @param node
	 */
	public static void deleteFavouriteJoke(Joke node) {
		// TODO Auto-generated method stub
		DataBase db = new DataBase(c);
		db.deleteFavouriteJoke(node);
	}

	/**
	 * 将评论进行urlEncode并发送评论，刷新评论后的页面
	 * 
	 * @param node
	 * @param comment
	 * @param sendCommentProcess
	 */
	public static void postComment(Joke node, String comment,
			ProcessCallback callback) {
		// TODO Auto-generated method stub
		comment = URLEncoder.encode(comment);
		String username = URLEncoder.encode(Setting.name);
		if(Setting.wifi!=null){
			username = URLEncoder.encode(Setting.name+"["+Setting.wifi+"]");
		}
		String url = genURL(COMMENT) + node.id + "/" + username + "/" + comment;
		InputStream is = StreamToolBox.loadStreamFromURL(url, callback);
		try {
			if (is != null) {
				String html = StreamToolBox.extractGZipStreamToString(is);
				ResultSet res = new ResultSet();
				res.action = Action.DETAIL;
				if (html != null) {
					res.html = html;
					callback.onSucess(res);
				} else {
					callback.onFailed(res);
				}
			} else {
				callback.onHttp404();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 生成随机用户名 user[uuidhashcode]
	 * 
	 * @return
	 */
	public static String genUserName() {
		String username = "user" + new Date().getTime();
		return username;
	}

	/**
	 * UUID
	 * 
	 * @return
	 */
	public static String genUserID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}

	public static void changeUserName(ProcessCallback callback, String name) {
		// TODO Auto-generated method stub
		InputStream is = StreamToolBox.loadStreamFromURL(genURL(CHANGEUSERNAME)
				+ URLEncoder.encode(name), callback);
		ResultSet res = Parser.parse(is, callback);
		res.action = Action.CHANGEUSERNAME;
		if (res.res.equals("1")) {
			callback.onSucess(res);
		} else {
			callback.onFailed(res);
		}
	}

	/**
	 * 返回文件URI路径 file:///humor/xxx.png
	 * 
	 * @param url
	 * @return
	 */

	public static String getCacheImage(String url) {
		// TODO Auto-generated method stub
		if (!url.startsWith("http://")) {
			Log.v("error", "wrong image cache URL : " + url);
			return null;
		}
		Cache c = Cache.getInstance();
		return "file:/" + c.getCacheImage(url);
	}

	public static void clearCache() {
		Cache c = Cache.getInstance();
		c.clear();
	}

	/**
	 * 返回缓存大小 byte单位
	 * 
	 * @return
	 */
	public static int getCacheSize() {
		return Cache.getInstance().getSize();
	}
}
